package com.rexolar.openapi.utlis;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * IpAddressUtil
 *
 * @author zhusiyu
 **/

@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class MacAddressUtil {

    private static final String UNKNOW_IP = "unknow";
    private static final String MAC = "BC0358B8C95F";

    public static void main(String[] args) {
        System.out.println(getMacAddress());
        System.out.println(MAC.equals(getMacAddress().trim()));
    }
    public static String getMacAddress() {
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                if (!isVirtualInterface(networkInterface)) { // 排除回环地址
                    byte[] mac = networkInterface.getHardwareAddress();
                    StringBuilder macAddresses = new StringBuilder();
                    if (mac != null) {
                        for (int i = 0; i < mac.length; i++) {
                            macAddresses.append(String.format("%02X", mac[i]));
                        }
                        return macAddresses.toString();
                    }
                }
            }
        } catch (SocketException e) {
            log.error("获取IP地址异常", e);
        }
        return UNKNOW_IP;
    }
    public static boolean isVirtualInterface(NetworkInterface networkInterface) throws SocketException {
        return networkInterface.getName().startsWith("veth") ||
                networkInterface.getName().startsWith("docker") ||
                networkInterface.isLoopback() ||
                networkInterface.isPointToPoint() ||
                networkInterface.isVirtual();
    }
}
